﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Dan.Common
{
    public class CacheHelper
    {
        /// <summary>
        ///   获取格式化的缓存键值
        /// </summary>
        /// <param name = "key">缓存键值</param>
        /// <returns>格式化后的缓存键值</returns>
        public static string GetCacheKey(string key)
        {
            return key.GetMd5();
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <typeparam name = "TData">要获取的数据类型</typeparam>
        /// <param name = "cacheGetter">缓存数据获取代理</param>
        /// <param name = "dataProvider">缓存原始数据代理</param>
        /// <param name = "cacheSetter">缓存数据设置代理</param>
        /// <param name = "useCache">是否使用缓存</param>
        /// <returns>数据</returns>
        public static TData Get<TData>(
            CacheGetterDelegate<TData> cacheGetter,
            CacheDataProviderDelegate<TData> dataProvider,
            CacheSetterDelegate<TData> cacheSetter, bool useCache)
        {
            TData data;
            if (useCache)
            {
                if (cacheGetter(out data))
                {
                    return data;
                }

                data = dataProvider();
                cacheSetter(data);
            }
            else
            {
                data = dataProvider();
            }

            return data;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <typeparam name="TData"></typeparam>
        /// <param name="dataProvider"></param>
        /// <param name="cacheSetter"></param>
        /// <param name="useCache"></param>
        /// <returns></returns>
        public static TData Update<TData>(
            CacheDataProviderDelegate<TData> dataProvider,
            CacheSetterDelegate<TData> cacheSetter, bool useCache)
        {
            TData data;

            data = dataProvider();
            if (useCache)
            {
                cacheSetter(data);
            }
            return data;
        }

        #region Delegates

        /// <summary>
        ///   缓存原始数据代理
        /// </summary>
        /// <typeparam name = "TData">要获取的数据类型</typeparam>
        /// <returns>数据对象</returns>
        public delegate TData CacheDataProviderDelegate<out TData>();

        /// <summary>
        ///   缓存数据获取代理
        /// </summary>
        /// <typeparam name = "TData">要获取的数据类型</typeparam>
        /// <param name = "data">数据对象</param>
        /// <returns>是否成功</returns>
        public delegate bool CacheGetterDelegate<TData>(out TData data);

        /// <summary>
        ///   缓存数据设置代理
        /// </summary>
        /// <typeparam name = "TData">要获取的数据类型</typeparam>
        /// <param name = "data">数据对象</param>
        public delegate void CacheSetterDelegate<TData>(TData data);

        #endregion
    }
}
